package com.shd.edanpei.presenter;

import android.app.Dialog;
import android.os.Bundle;
import android.view.View;

import com.shd.edanpei.R;
import com.shd.edanpei.base.rxbus.Subscribe;
import com.shd.edanpei.bean.ImgInfoBean;
import com.shd.edanpei.ui.activity.CarNeedDataActivity1;
import com.shd.edanpei.ui.activity.CustomerInfoActivity;
import com.shd.edanpei.ui.activity.FileListActivity;
import com.shd.edanpei.ui.activity.FileListPersonalAndEnterpActivity;
import com.shd.edanpei.ui.activity.HouseNeedDataActivity1;
import com.shd.edanpei.ui.activity.PersionalActivity;
import com.shd.edanpei.ui.activity.UpdateLocation;
import com.shd.edanpei.base.BasePresenterImpl;
import com.shd.edanpei.common.Constant;
import com.shd.edanpei.base.data.RxBusCode;
import com.shd.edanpei.base.dialog.DialogUtil;
import com.shd.edanpei.base.network.api.ApiCreator;
import com.shd.edanpei.base.network.exception.ResponeThrowable;
import com.shd.edanpei.base.network.model.NoDataResponse;
import com.shd.edanpei.base.network.rx.BaseObserver;
import com.shd.edanpei.base.network.rx.RxTransformer;
import com.shd.edanpei.base.rxbus.RxBus;
import com.shd.edanpei.bean.OrderListModel;
import com.shd.edanpei.bean.StatusBean;
import com.shd.edanpei.bean.PagingModel;
import com.shd.edanpei.presenter.contract.ManagerContract;
import com.shd.edanpei.order.ItemDialog;
import com.shd.edanpei.order.OrderApiService;
import com.shd.edanpei.enums.OrderTypeEnum;
import com.shd.edanpei.enums.StatusEnum;
import com.shd.edanpei.util.LayoutUtils;
import com.shd.edanpei.util.ToastUtil;

import java.util.ArrayList;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by mc on 2018/9/25.
 * yang-wen-wen
 */

public class ManagerPresenter extends BasePresenterImpl<ManagerContract.ManagerIView> implements ManagerContract.ManageIPresenter {

    private int currentPage;
    private int totalPage;
    private Dialog updateDialog;

    public ManagerPresenter(ManagerContract.ManagerIView mView) {
        super(mView);
        RxBus.get().register(this);
    }

    @Override
    public void refresh(int orderType, int orderStatus) {
        currentPage = 1;
        ApiCreator.getApi().orderList(orderType, orderStatus, currentPage)//101
                .compose(RxTransformer.<PagingModel<OrderListModel>>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<PagingModel<OrderListModel>>() {
                    @Override
                    protected void onSuccess(PagingModel<OrderListModel> data) {
                        if (data != null && data.getList().size() > 0) {
                            totalPage = data.getTotalPage();
                            mBaseIView.getAdapter().setNewData(data.getList());
                            if (currentPage >= totalPage) {
                                mBaseIView.getAdapter().loadMoreEnd();
                            } else {
                                mBaseIView.getAdapter().loadMoreComplete();
                            }
                            currentPage++;
                        } else {
                            mBaseIView.getAdapter().setNewData(null);
                            mBaseIView.getAdapter()
                                    .setEmptyView(LayoutUtils.getNullLayout(mBaseIView.getContext(), R.drawable.pic_null_bg, "暂无相关订单"));
                        }
                    }

                    @Override
                    public void onFailure(ResponeThrowable throwable) {
                        mBaseIView.getAdapter()
                                .setEmptyView(LayoutUtils.getNullLayout(mBaseIView.getContext(), R.drawable.pic_null_bg, "暂无相关订单"));
                    }

                    @Override
                    public void onFinish() {
                        if (mBaseIView.getRefreshLayout() != null) {
                            mBaseIView.getRefreshLayout().setRefreshing(false);
                        }
                    }
                });
    }

    @Override
    public void loadMore(int orderType, int orderStatus) {
        ApiCreator.getApi().orderList(orderType, orderStatus, currentPage)
                .compose(RxTransformer.<PagingModel<OrderListModel>>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<PagingModel<OrderListModel>>() {
                    @Override
                    protected void onSuccess(PagingModel<OrderListModel> data) {
                        if (data != null && data.getList().size() > 0) {
                            mBaseIView.getAdapter().addData(data.getList());
                            if (currentPage >= totalPage) {
                                mBaseIView.getAdapter().loadMoreEnd();
                            } else {
                                mBaseIView.getAdapter().loadMoreComplete();
                            }
                            currentPage++;
                        } else {
                            mBaseIView.getAdapter().loadMoreEnd();
                        }
                    }

                    @Override
                    public void onFailure(ResponeThrowable throwable) {
                        mBaseIView.getAdapter().loadMoreEnd();
                    }
                });
    }


    @Override
    public void userUndo(final int orderID, final int orderType, final int index, final boolean payDeposit) {
        new ItemDialog(mBaseIView.getContext(), "撤销理由", R.array.user_undo_reason, new ItemDialog.Listener() {
            @Override
            public void setInfo(String str) {
                mBaseIView.showLoading("撤销中...");
                OrderApiService.userUndo(str, orderID, orderType, index, payDeposit, new OrderApiService.Listener() {
                    @Override
                    public void onFinish() {
                        mBaseIView.stopLoading();
                    }
                });
            }
        }).show();
    }

    @Override
    public void bankUndo(final int orderID, final int orderType, final int index, final boolean payDeposit) {
        new ItemDialog(mBaseIView.getContext(), "撤销理由", R.array.bank_undo_reson, new ItemDialog.Listener() {
            @Override
            public void setInfo(String str) {
                mBaseIView.showLoading("撤销中...");
                OrderApiService.bankUndo(str, orderID, orderType, index, new OrderApiService.Listener() {
                    @Override
                    public void onFinish() {
                        mBaseIView.stopLoading();
                    }
                });

            }
        }).show();
    }

//    @Override
//    public void remove(final int orderID, final int orderType, final int index, final int type) {
//        DialogUtil.infoDialog(mBaseIView.getContext(), "温馨提示", "您确定要删除此订单吗？", null, null, new DialogUtil.SureListener() {
//            @Override
//            public void sure() {
//                if (type == Constant.ME_ORDER) {
//                    ApiCreator.getApi().userDelete(orderID, orderType)
//                            .compose(RxTransformer.<NoDataResponse>errorHandle())
//                            .observeOn(AndroidSchedulers.mainThread())
//                            .subscribe(new BaseObserver<NoDataResponse>() {
//                                @Override
//                                protected void onSuccess(NoDataResponse data) {
//                                    mBaseIView.getAdapter().remove(index);
//                                    checkList();
//                                    ToastUtil.showToast("删除成功");
//                                }
//                            });
//                } else if (type == Constant.SHARE_ORDER) {
//                    ApiCreator.getApi().deleteOrder(orderID, orderType)
//                            .compose(RxTransformer.<NoDataResponse>errorHandle())
//                            .observeOn(AndroidSchedulers.mainThread())
//                            .subscribe(new BaseObserver<NoDataResponse>() {
//                                @Override
//                                protected void onSuccess(NoDataResponse data) {
//                                    mBaseIView.getAdapter().remove(index);
//                                    checkList();
//                                    ToastUtil.showToast("删除成功");
//                                }
//                            });
//                }
//
//
//            }
//        });
//
//    }

    @Override
    public void userRemove(final int orderID, final int orderType, final int index) {
        DialogUtil.infoDialog(mBaseIView.getContext(), "温馨提示", "您确定要删除此订单吗？", null, null, new DialogUtil.SureListener() {
            @Override
            public void sure() {
                ApiCreator.getApi().userDelete(orderID, orderType)
                        .compose(RxTransformer.<NoDataResponse>errorHandle())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<NoDataResponse>() {
                            @Override
                            protected void onSuccess(NoDataResponse data) {
                                mBaseIView.getAdapter().remove(index);
                                checkList();
                                ToastUtil.showToast("删除成功");
                            }
                        });
            }
        });
    }

    @Override
    public void bankRemove(final int orderID, final int orderType, final int index) {
        DialogUtil.infoDialog(mBaseIView.getContext(), "温馨提示", "您确定要删除此订单吗？", null, null, new DialogUtil.SureListener() {
            @Override
            public void sure() {
                ApiCreator.getApi().deleteOrder(orderID, orderType)
                        .compose(RxTransformer.<NoDataResponse>errorHandle())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<NoDataResponse>() {
                            @Override
                            protected void onSuccess(NoDataResponse data) {
                                mBaseIView.getAdapter().remove(index);
                                checkList();
                                ToastUtil.showToast("删除成功");
                            }
                        });

            }
        });
    }

    @Override
    public void againApply(final int orderID, final int orderType, final int index) {
        ApiCreator.getApi().againApply(orderID, orderType)
                .compose(RxTransformer.<NoDataResponse>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<NoDataResponse>() {
                    @Override
                    protected void onSuccess(NoDataResponse data) {
                        RxBus.get().send(RxBusCode.REFRESH_ORDER_STATUS, new StatusBean(index, StatusEnum.unpaid.getStatus()));
                        DialogUtil.hintDialog(mBaseIView.getContext(), R.drawable.ic_success, "申请成功");
                    }
                });
    }

    @Override
    public void sureGetLone(Bundle bundle) {
        final int orderID = bundle.getInt(Constant.ORDER_ID);
        final int orderType = bundle.getInt(Constant.ORDER_TYPE);
        final int index = bundle.getInt(Constant.INDEX);
        DialogUtil.infoDialog(mBaseIView.getContext(), "立即确认", "请务必确认您已收到终审金额", null, null, new DialogUtil.SureListener() {
            @Override
            public void sure() {
                ApiCreator.getApi().sureGetLoan(orderID, orderType)
                        .compose(RxTransformer.<NoDataResponse>errorHandle())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<NoDataResponse>() {
                            @Override
                            protected void onSuccess(NoDataResponse data) {
                                RxBus.get().send(RxBusCode.REFRESH_ORDER_STATUS, new StatusBean(index, StatusEnum.success.getStatus()));
                                DialogUtil.hintDialog(mBaseIView.getContext(), R.drawable.ic_success, "确认成功");
                            }
                        });
            }
        });

    }

    @Override
    public void updataOrder(final Bundle bundle, final int orderID, final int orderType, final int status) {
        bundle.putInt(Constant.FROM, 1);
        View view = View.inflate(mBaseIView.getContext(), R.layout.dialog_updata_order_select, null);

        updateDialog = new Dialog(mBaseIView.getContext(), R.style.dialog);
        updateDialog.setContentView(view);
        updateDialog.setCanceledOnTouchOutside(true);

        view.findViewById(R.id.update_location).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBaseIView.startActivity(UpdateLocation.class, bundle);
//                    updateDialog.dismiss();
            }
        });
        view.findViewById(R.id.update_info).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bundle.putInt(Constant.FROM, CustomerInfoActivity.UPDATA);
                mBaseIView.startActivity(CustomerInfoActivity.class, bundle);
//                    updateDialog.dismiss();
            }
        });
        view.findViewById(R.id.update_data).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bundle.putInt(Constant.FROM, 1);
                if (orderType == OrderTypeEnum.car.getKey()) {
                    mBaseIView.startActivity(CarNeedDataActivity1.class, bundle);
                } else if (orderType == OrderTypeEnum.house.getKey()) {
                    mBaseIView.startActivity(HouseNeedDataActivity1.class, bundle);
                }else if(orderType==OrderTypeEnum.personal.getKey()){
                    mBaseIView.startActivity(PersionalActivity.class, bundle);
                }else if(orderType==OrderTypeEnum.enterprise.getKey()){
                    mBaseIView.startActivity(PersionalActivity.class, bundle);
                }
//                    updateDialog.dismiss();
            }
        });
        view.findViewById(R.id.update_file).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bundle.putInt(Constant.FROM, 1);
                bundle.putBoolean("isMarry", isMarry);
                bundle.putBoolean("isCar", isCar);
                bundle.putBoolean("other", other);
                bundle.putBoolean("company", company);

                if(orderType==OrderTypeEnum.car.getKey()||orderType==OrderTypeEnum.house.getKey()){
                    mBaseIView.startActivity(FileListActivity.class, bundle);
                }else{
                    mBaseIView.startActivity(FileListPersonalAndEnterpActivity.class, bundle);
                }

//                    updateDialog.dismiss();
            }
        });
        view.findViewById(R.id.tv_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sureUpdate(orderID, status, bundle.getInt(Constant.INDEX));
            }
        });
        updateDialog.show();
    }

    private boolean isMarry = false;

    @Subscribe(code = RxBusCode.isMarry)
    public void setMarry(Boolean b) {
        isMarry = b;
    }


    private boolean isCar = false;
    @Subscribe(code = RxBusCode.isCar)
    public void setCar(Boolean b){
        isCar = b;
    }

    private boolean other = false;

    @Subscribe(code = RxBusCode.other)
    public void setOther(Boolean b){
        other = b;
    }

    private boolean company = false;
    @Subscribe(code = RxBusCode.company)
    public void setCompany(Boolean b){
        company = b;
    }

    private boolean isHourse = false;
    @Subscribe(code =RxBusCode.ishourse)
    public  void setIsHourse(Boolean b){
        isHourse=b;
    }
    private boolean isInsurance = false;
    @Subscribe(code =RxBusCode.isinsurance)
    public  void setIsInsurance(Boolean b){
        isInsurance=b;
    }
    private boolean isFun = false;
    @Subscribe(code =RxBusCode.isfun)
    public  void setIsFun(Boolean b){
        isFun=b;
    }


    private void sureUpdate(final int orderID, final int status, final int index) {
        ApiCreator.getApi().getFileData(orderID)
                .compose(RxTransformer.<ImgInfoBean>errorHandle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<ImgInfoBean>() {
                    @Override
                    protected void onSuccess(ImgInfoBean data) {
                        ArrayList<String> list = new ArrayList<>();
                        list.add("");

                        if (data.getRoomCert().size() == 0 && isHourse) {
                            ToastUtil.showToast("请上房产证信息");
                            return;
                        }
                        if (data.getCarWarranty().size() == 0 && isInsurance) {
                            ToastUtil.showToast("请上传保单信息");
                            return;
                        }

                        //首先检查是否有为提交的文件
                        if (status == StatusEnum.cancel.getStatus()
                                || status == StatusEnum.waitRepay.getStatus()) {
                            mBaseIView.showLoading("");
                            ApiCreator.getApi().comfirmUpdate(orderID)
                                    .compose(RxTransformer.<NoDataResponse>errorHandle())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new BaseObserver<NoDataResponse>() {
                                        @Override
                                        protected void onSuccess(NoDataResponse data) {


                                            if (status == StatusEnum.cancel.getStatus()) {
                                                RxBus.get().send(RxBusCode.REFRESH_ORDER_STATUS, new StatusBean(index, StatusEnum.unpaid.getStatus()));
                                            } else {
                                                RxBus.get().send(RxBusCode.REFRESH_ORDER_STATUS, new StatusBean(index, StatusEnum.applying.getStatus()));
                                            }
                                            updateDialog.dismiss();
                                        }

                                        @Override
                                        public void onFinish() {
                                            mBaseIView.stopLoading();
                                        }

                                        @Override
                                        public void onFailure(ResponeThrowable throwable) {
                                            ToastUtil.showToast(throwable.getMessage());
                                        }
                                    });
                        }
                    }
                });



    }


    public void checkList() {
        //判断列表是否还有数据
        if (mBaseIView.getAdapter().getData().size() == 0) {
//            mBaseIView.getAdapter().setEmptyView(getNullLayout());
        }
    }

}
